//
//  XQAuthenticationController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/22.
//

#import "XQAuthenticationController.h"
#import "XQIdentityPersonInfoController.h"
#import "XQIdentityJobController.h"
#import "XQEmergencyController.h"
#import "XQBindAccountController.h"
#import "XQHomeTopCardView.h"
#import "XQAuthenticationCell.h"
#import "XQprivacyView.h"
#import "XQPrivacyPopView.h"
#import "XQPopupAnimView.h"
#import "XQButton.h"
#import "XQIdentityController.h"
#import "XQAuthendicationListModel.h"

@interface XQAuthenticationController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIView *mainView;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) XQHomeTopCardView *topCardView;
@property (nonatomic,strong) UIButton *applyButton;
@property (nonatomic,strong) UILabel *certificationLb;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) XQprivacyView *privacyView;
@property (nonatomic,strong) XQButton *bottomButton;
@property (nonatomic,copy) NSDictionary *dataDic;

@property (nonatomic,strong) NSMutableArray<XQAuthendicationListModel *> *dataSource;

@end

@implementation XQAuthenticationController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeUI];
    [self makeConstraints];
 
    [XQHUD showLoadingInView:self.view];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshData];
    [self startLocation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self stopLocation];
}

- (void)makeUI {
    self.view.backgroundColor = kCardColor;
    [self.view insertSubview:self.scrollView belowSubview:self.navigationBar];
    [self.scrollView addSubview:self.mainView];
    [self.mainView addSubview:self.topCardView];
    [self.mainView addSubview:self.applyButton];
    [self.mainView addSubview:self.certificationLb];
    [self.mainView addSubview:self.tableView];
    [self.mainView addSubview:self.privacyView];
    [self.mainView addSubview:self.bottomButton];
}

- (void)makeConstraints {
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].topHeight);
        make.left.right.equalTo(@0);
        make.bottom.offset(-[UIScreen mainScreen].bottomHeight);
    }];
    [self.mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.mas_equalTo([UIScreen mainScreen].width);
    }];
    [self.topCardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(8);
        make.left.right.equalTo(@0);
        make.height.mas_equalTo(220);
    }];
    [self.applyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topCardView.mas_bottom).offset(10);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(45);
    }];
    [self.certificationLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.applyButton.mas_bottom).offset(20);
        make.left.equalTo(@12);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.certificationLb.mas_bottom).offset(10);
        make.left.right.equalTo(@0);
        make.height.mas_equalTo(54 * 5);
    }];
    [self.privacyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom).offset(40);
        make.left.equalTo(@36);
    }];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.privacyView.mas_bottom).offset(20);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-20);
    }];
}

- (void)refreshData {
    NSDictionary *dic = @{
        @"accommodate" : self.cardId
    };
    
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/fax"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        
        if ([responseObject[@"concept"] integerValue] == 0) {
            self.dataDic = responseObject[@"accomplish"];
            [self updatePageData];
            
        }
    }];
}

- (void)updatePageData {
    [self setNav];
    [self setCardData];
    [self setTabData];
    [self setPricyData];
}

- (void)setNav {
    NSDictionary *cardDic = self.dataDic[@"budgeted"];
    [self.navigationBar setTitle:cardDic[@"airborne"]];
}


- (void)setCardData {
    NSDictionary *cardDic = self.dataDic[@"budgeted"];
    
    [self.topCardView setPrice:[cardDic[@"greater"] description]];
    
    NSDictionary *motivated = cardDic[@"motivated"];
    
    NSDictionary *astronauts = motivated[@"astronauts"];
    
    NSDictionary *tiangong = motivated[@"tiangong"];
    
    [self.bottomButton setTitle:cardDic[@"hughes"]];
    [self.applyButton setTitle:@"Certification List" forState:UIControlStateNormal];
    
    [self.topCardView setTopValue:cardDic[@"maneuver"]];
    [self.topCardView setConflicts:tiangong[@"won"]];
    [self.topCardView setEncountered:astronauts[@"won"]];
    [self.topCardView setArticles:tiangong[@"aboard"]];
    [self.topCardView setTrademark:astronauts[@"aboard"]];
}

- (void)setTabData {
    NSArray *tableDatas = self.dataDic[@"delegates"];
    
    self.tableView.hidden = tableDatas.count == 0;
    
    self.certificationLb.hidden = tableDatas.count == 0;
    
    [self.dataSource removeAllObjects];
    for (int i = 0; i < tableDatas.count; i++) {
        NSDictionary *dic = tableDatas[i];
        XQAuthendicationListModel *model = [XQAuthendicationListModel yy_modelWithDictionary:dic];
        [self.dataSource addObject:model];
    }
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(54 * self.dataSource.count);
    }];
    
    [self.tableView reloadData];
}

- (void)setPricyData {
    NSDictionary *players = self.dataDic[@"players"];
    NSString *title = players[@"won"];
    
    if ([title containsString:@"||"]) {
        NSArray *list = [title componentsSeparatedByString:@"||"];
        if (list.count == 2) {
            [self.privacyView setPrivacyPrefix:list[0]];
            [self.privacyView setPrivacyValue:list[1]];
        }
    }
    
    self.privacyView.hidden = title.length == 0;
    
    [self.privacyView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom).offset(title.length ? 40 : 20);
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XQAuthenticationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XQAuthenticationCell" forIndexPath:indexPath];
    [cell setIndex:indexPath.row + 1];
    [cell setModel:self.dataSource[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    XQAuthendicationListModel *model = self.dataSource[indexPath.row];
    
    if ([model.evasive isEqualToString:@"1"]) {
        [self didSelectToControllerWithTitle:model.won nations:model.nations aviation:model.aviation];
        return;
    }
    
    NSDictionary *emails = self.dataDic[@"emails"];
    
    if (emails.count) {
        NSString *title = emails[@"won"];
        NSString *aviation = emails[@"aviation"];
        NSString *nations = emails[@"nations"];
        
        [self didSelectToControllerWithTitle:title nations:nations aviation:aviation];
        
        return;
    }
}

#pragma mark - private

- (void)bottomClick {
    
    NSDictionary *emails = self.dataDic[@"emails"];
    
    NSString *nations = emails[@"nations"];
    
    if (emails.count && nations.length) {
        NSString *title = emails[@"won"];
        NSString *aviation = emails[@"aviation"];
        
        [self didSelectToControllerWithTitle:title nations:nations aviation:aviation];
        
        return;
    }
    
    if (!self.privacyView.radioButton.selected && !self.privacyView.hidden) {
        [XQToast showMsg:@"Please read and agree to the Privacy Policy"];
        return;
    }
    NSDictionary *budgetedDic = self.dataDic[@"budgeted"];
    
    NSString *paging = budgetedDic[@"ntia"];
    NSString *greater = budgetedDic[@"greater"];
    NSString *constituted = budgetedDic[@"constituted"];
    NSString *encounters = budgetedDic[@"encounters"];
    
    NSDictionary *dic = @{
        @"paging" : paging,
        @"greater" : greater,
        @"constituted" : constituted,
        @"encounters" : encounters
    };
    
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/unmodified"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];  
        if ([responseObject[@"concept"] integerValue] == 0) {
            
            [self reportRisk:paging];
            
            NSDictionary *accomplish = responseObject[@"accomplish"];
            if (self.backHandle) {
                self.backHandle(accomplish[@"aviation"],YES);
            }
        }else {
            [XQToast showMsg:responseObject[@"loon"]];
        }
    }];
}

- (void)reportRisk:(NSString *)orderId {
    long long time = [XQTimeTool nowTimeStamp];
    [XQGoogleMarket reportRiskWithType:@"9" longitude:self.longitude latitude:self.latitude startTime:time endTime:time orderId:orderId];
}

- (void)pricyProtocolClick {
    XQWebViewController *controller = [XQWebViewController new];
    
    NSDictionary *players = self.dataDic[@"players"];
    NSString *url = players[@"disrupted"];
    
    controller.url = [XQNetManager getWebUrlAbsolutePath:url];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)didSelectToControllerWithTitle:(NSString *)title nations:(NSString *)nations aviation:(NSString *)aviation {
    XQBaseViewController *controller;
    
    if ([nations isEqualToString:@"stateda"]) {
        controller = [[XQIdentityController alloc] init];
    }else if ([nations isEqualToString:@"statedb"]) {
        controller = [[XQIdentityPersonInfoController alloc] init];
    }else if ([nations isEqualToString:@"statedc"]) {
        controller = [[XQIdentityJobController alloc] init];
    }else if ([nations isEqualToString:@"statedd"]) {
        controller = [[XQEmergencyController alloc] init];
    }else if ([nations isEqualToString:@"statede"]) {
        if (aviation.length) {
            XQWebViewController *controller = [XQWebViewController new];
            controller.url = [XQNetManager getWebUrlAbsolutePath:aviation];
            [self.navigationController pushViewController:controller animated:YES];
        }else {
            controller = [[XQBindAccountController alloc] init];
        }
    }
    controller.cardId = self.cardId;
    controller.topTitle = title;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - lazy

- (UIView *)mainView {
    if (!_mainView) {
        _mainView = [[UIView alloc] init];
    }
    return _mainView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
    }
    return  _scrollView;
}

- (XQHomeTopCardView *)topCardView {
    if (!_topCardView) {
        _topCardView = [[XQHomeTopCardView alloc] init];
        [_topCardView setUserInteractionEnabled:YES];
//        [_topCardView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bottomClick)]];
    }
    return _topCardView;
}

- (UIButton *)applyButton {
    if (!_applyButton) {
        _applyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _applyButton.layer.cornerRadius = 22.5;
        _applyButton.backgroundColor = [UIColor colorWithHexString:@"#4C1DEE"];
        _applyButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [_applyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [_applyButton addTarget:self action:@selector(bottomClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _applyButton;
}

- (UILabel *)certificationLb {
    if (!_certificationLb) {
        _certificationLb = [[UILabel alloc] init];
        _certificationLb.text = @"Certification";
        _certificationLb.font = [UIFont boldSystemFontOfSize:16];
        _certificationLb.textColor = kBlackTextColor;
        _certificationLb.hidden = YES;
    }
    return _certificationLb;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView setScrollEnabled:NO];
        _tableView.hidden = YES;
        [_tableView registerClass:[XQAuthenticationCell class] forCellReuseIdentifier:@"XQAuthenticationCell"];
    }
    return _tableView;
}

- (NSMutableArray<XQAuthendicationListModel *> *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (XQprivacyView *)privacyView {
    if (!_privacyView) {
        _privacyView = [[XQprivacyView alloc] initWithViewController:self];
        _privacyView.radioButton.selected = YES;
        @weakify(self);
        _privacyView.privacyHandle = ^{
            @strongify(self);
            [self pricyProtocolClick];
        };
    }
    return _privacyView;
}

- (XQButton *)bottomButton {
    if (!_bottomButton) {
        _bottomButton = [[XQButton alloc] initWithTitle:@""];
        @weakify(self);
        _bottomButton.onTapHandle = ^{
            @strongify(self);
            [self bottomClick];
        };
    }
    return _bottomButton;
}


@end
